package com.roger.myHome.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.roger.myHome.domain.TbWeather;
import com.roger.myHome.entity.LoginUser;
import com.roger.myHome.mapper.WeatherMapper;
import com.roger.myHome.service.LoginService;
import com.roger.myHome.service.MenuService;
import com.roger.myHome.util.DateUtil;
import com.roger.myHome.util.JwtUtil;
import com.roger.myHome.util.StringUtils;
import com.roger.myHome.util.SystemUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

@Controller
@RequestMapping("/login")
@Slf4j
public class LoginController {
    @Resource
    private LoginService loginService;

    @Resource
    private MenuService menuService;

    @Resource
    private WeatherMapper weatherMapper;

    static final Long ONE_MINUTE = 1000 * 60L;

    @PostMapping(produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String doLogin(HttpServletRequest request) {
        String loginName = request.getParameter("loginName");
        String password = request.getParameter("password");
        log.info("[{}],[{}]发起登录",loginName, DateUtil.getCurrentTime());

        LoginUser loginUser = loginService.loginUser(loginName, password);
        Map<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("result", "success");

        if (loginUser == null) {
            hashMap.put("result", "false");
        } else {
            hashMap.put("result", "success");
            hashMap.put("token", JwtUtil.getJwtToken(loginUser.getId().toString(), loginName, 1000 * 60 * 60));
            hashMap.put("expireTime", "180000");
            hashMap.put("refreshToken", JwtUtil.getJwtToken(loginUser.getId().toString(),loginName, 1000 * 60 * 60 * 24));
            hashMap.put("username", loginUser.getUsername());

            LambdaQueryWrapper<TbWeather> lambda = Wrappers.lambdaQuery();
            lambda.eq(TbWeather::getYmd, DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
            List<TbWeather> tbWeatherList = weatherMapper.selectList(lambda);
            String weather = StringUtils.javabeanToJson(tbWeatherList.get(0));
            hashMap.put("weather",weather);

            List<String> menuList = menuService.selectNotNull();
            SystemUtil.setMenuUrlList(menuList);

        }
        return StringUtils.getJSONString(hashMap);
    }

    /**
     * 以post或get方式调用对方接口方法，
     * @param pathUrl
     */
    public static void doPostOrGet(String pathUrl, String data){
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        try {
            URL url = new URL(pathUrl);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //请求方式
            conn.setRequestMethod("GET");
            //conn.setRequestMethod("GET");

            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            //DoOutput设置是否向httpUrlConnection输出，DoInput设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(5000); // 5秒 连接主机的超时时间（单位：毫秒）
            conn.setReadTimeout(5000);// 5秒 从主机读取数据的超时时间（单位：毫秒）
            /**
             * 下面的三句代码，就是调用第三方http接口
             */
            //获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //发送请求参数即数据
            out.write(data);
            //flush输出流的缓冲
            out.flush();

            /**
             * 下面的代码相当于，获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is));
            JSONObject dd1 = new JSONObject();
            JSONObject jb = new JSONObject();
            String str = "";
            char[] chs = new char[300];
            while ((str = br.readLine()) != null){
                result += str;
                System.out.println(str);
            }

            String aa = "";
            String[]  strs = result.split(",");
            for(int i=0,len=strs.length;i<len;i++){

                aa=strs[4].toString();

            }
            System.out.println("========="+aa.substring(9, 15) );
//            System.out.println(result);

            //关闭流
            is.close();
            //断开连接，disconnect是在底层tcp socket链接空闲时才切断，如果正在被其他线程使用就不切断。
            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (out != null){
                    out.close();
                }
                if (br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        /**
         *手机信息查询接口：http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=手机号
         　　　　 *　　　　　　http://api.showji.com/Locating/www.showji.com.aspx?m=手机号&output=json&callback=querycallback
         */
        doPostOrGet("https://api.help.bj.cn/apis/weather2d/?id=苏州", "");
    }



}
